package com.gtcom.sdk;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.widget.Toast;

import com.gtcom.sdk.asr.GTRecognitionConfig;
import com.gtcom.sdk.asr.GTRecognitionListener;
import com.gtcom.sdk.asr.GTRecognitionServiceListener;
import com.gtcom.sdk.asr.GTRecognizer;
import com.gtcom.sdk.bean.ASRMessage;
import com.gtcom.sdk.language.LanguageBean;
import com.gtcom.sdk.utils.RecordThread;
import com.gtcom.sdk.utils.SignUtils;
import com.gtcom.sdk.utils.StringUtils;
import com.gtcom.sdk.translator.GTTranslationConfig;
import com.gtcom.sdk.translator.GTTranslationListener;
import com.gtcom.sdk.translator.GTTranslator;

import org.json.JSONObject;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;


public class AndroidService {
    //#region asr
    //选中的语言
    private LanguageBean currentLanguage = new LanguageBean("zh-CN", "中文普通话");
    //结果列表
    private List<ASRMessage> mList = new ArrayList<>();
    //录音线程
    private RecordThread recordThread;
    private void asr_init() {
        printLog("onCreate");
        //设置ASR监听
        GTRecognizer.setGTRecognitionListener(new GTRecognitionListener() {
            @Override
            public void onTextResult(String result) {
                try {
                    if (result.equals("msgEnd")) {
                        //识别结束
                    } else {
                        JSONObject jsonObject = new JSONObject(result);
                        if (jsonObject.has("text")) {
                            String recognition = jsonObject.getString("text");
                            String order = jsonObject.getString("order");
                            String state = jsonObject.getString("state");
                            if (!StringUtils.isNullOrEmpty(recognition)) {

                                if(state.equals("end"))asrResult(recognition);
                                else printLog(recognition+order+state);
                            }
                        }
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                    printLog(ex.toString());
                }
            }
        });

        printLog("onCreate Succeed");
    }
    private void asr_close() {
        printLog("onDestroy");
        //在活动结束时，记得释放资源
        GTRecognizer.close();
        if (recordThread != null) {
            recordThread.stopRecord();
        }
    }
    private void asr_open(String language) {
        printLog("openASR");
        GTRecognitionConfig config = new GTRecognitionConfig();
        config.key = "0jia87da8u67agdjaaai8aihajdvadad";
        config.salt = SignUtils.getRandom();
        config.sign = SignUtils.getSign(config.key, "5167913736", config.salt);
        config.language = language;
        //config.extraCode = "";
        printLog("开启识别服务：" + config.language);
        GTRecognizer.open(getActivity(), config, new GTRecognitionServiceListener() {
            @Override
            public void onSuccess() {
                //ASR服务启动成功
                printLog("onSuccess ASR服务已连接...");
            }
            @Override
            public void onError(int errorCode, String errorMessage) {
                //启动失败
                printLog("onError  Code =  " + errorCode + " Message = " + errorMessage);
                //将错误信息也输出到聊天框中
                ASRMessage errMessage = new ASRMessage();
                errMessage.text = errorMessage;
                errMessage.errorCode = errorCode;
                printLog(errorMessage);
                //关闭录音
                if (recordThread != null) {
                    recordThread.stopRecord();
                }
            }

        });
    }
    private void asr_start() {
        printLog("开始识别");
        GTRecognizer.start();
        if (recordThread != null && recordThread.isAlive()) {
            recordThread.stopRecord();
        }
        recordThread = new RecordThread();
        recordThread.startRecord();
    }
    private void asr_stop() {
        printLog("停止识别");
        GTRecognizer.stop();
        if (recordThread != null) {
            recordThread.stopRecord();
        }
    }
    private void asrResult(String content){
        callUnity("AndroidService","ASRResult", content);
    }
    //#endregion
    //#region translate
    //选择的源语言和目标语言
    LanguageBean nativeLanguage = new LanguageBean("zh-CN", "中文普通话");
    LanguageBean targetLanguage = new LanguageBean("en-US", "英语（美国）");

    private void translate(String text) {
        GTTranslationConfig config = new GTTranslationConfig();
        config.key = "0jia87da8u67agdjaaai8aihajdvadad";
        config.salt = SignUtils.getRandom();
        config.sign = SignUtils.getSign(config.key, "5167913736", config.salt);
        config.from = nativeLanguage.getLanguageCode();
        config.to = targetLanguage.getLanguageCode();
        //config.extraCode = "";
        GTTranslator.translate(getActivity(), config, text, new GTTranslationListener() {
            @Override
            public void onTranslate(String result) {
                try{
                    JSONObject jsonObject = new JSONObject(result);
                    translateResult(jsonObject.getJSONObject("data").optString("srcTxt"));
                }catch (Exception ex){
                    ex.printStackTrace();
                    printLog(ex.toString());
                }
            }

            @Override
            public void onError(int errorCode, String errorMessage) {
                printLog(errorMessage);
            }
        });
    }
    private void translateResult(String content){
        callUnity("AndroidService","TranslateResult", content);
    }
    //#endregion
    //#region android <~> unity
    private void printLog(String s){
        showToast(s);
    }

    private boolean showToast(String content){
        //Toast.makeText(getActivity(),content, Toast.LENGTH_SHORT).show();
        //这里是主动调用Unity中的方法，该方法之后unity部分会讲到
        callUnity("AndroidService","FromAndroid", content);
        return true;
    }

    private boolean callUnity(String gameObjectName, String functionName, String args){
        try {
            Class<?> classtype = Class.forName("com.unity3d.player.UnityPlayer");
            Method method =classtype.getMethod("UnitySendMessage", String.class,String.class,String.class);
            method.invoke(classtype,gameObjectName,functionName,args);
            return true;
        } catch (ClassNotFoundException e) {

        } catch (NoSuchMethodException e) {

        } catch (IllegalAccessException e) {

        } catch (InvocationTargetException e) {

        }
        return false;
    }

    private Activity _unityActivity ;

    private Activity getActivity(){
        if(null == _unityActivity) {
            try {
                Class<?> classtype = Class.forName("com.unity3d.player.UnityPlayer");
                Activity activity = (Activity) classtype.getDeclaredField("currentActivity").get(classtype);
                _unityActivity = activity;
            } catch (ClassNotFoundException e) {

            } catch (IllegalAccessException e) {

            } catch (NoSuchFieldException e) {

            }
        }
        return _unityActivity;
    }
    //#endregion

    private void callApp(String packagename,String calldata)
    {
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent = getActivity().getPackageManager().getLaunchIntentForPackage(packagename);
        intent.putExtra("call",calldata);
        getActivity().startActivity(intent);
    }
    private void onCall()
    {
        String value = getActivity().getIntent().getStringExtra("call");
        if(value!=null) callUnity("AndroidService","OnCallResult",value);
    }
}
